﻿using LitJson;
using ServerSocket.common;
using ServerSocket.dao;
using ServerSocket.entity;
using ServerSocket.server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServerSocket.controller
{
    class UserController:BaseController
    {

        /// <summary>
        /// 用户操作对象
        /// </summary>
        private UserDao userDao = new UserDao();

        /// <summary>
        /// 构造方法
        /// </summary>
        public UserController() {
            requestCode = common.RequestCode.User;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public string Login(string data, Client client, Server server)
        {
            Console.WriteLine("登录请求：" + data);
            User user = JsonMapper.ToObject<User>(data);
            User findUser = new User();
            for (int i = 0; i < server.ClientList.Count; i++)
            {
                Client c = server.ClientList[i];
                User u = c.User;
                if (u != null)
                {
                    if (u.Username.Equals(user.Username))
                    {
                        findUser = u;
                        if (findUser.Password.Equals(u.Password))
                        {
                            return R.Success(findUser);
                        }
                        else
                        {
                            return R.Fail("密码错误");
                        }
                    }
                }
            }
            return R.Fail("未找到该用户");
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        public string Register(string data, Client client, Server server)
        {
            Console.WriteLine("注册请求：" + data);
            User user = JsonMapper.ToObject<User>(data);
            bool flag = false;
            for (int i = 0; i < server.ClientList.Count; i++)
            {
                Client c = server.ClientList[i];
                User u = c.User;
                if (u != null)
                {
                    if (u.Username.Equals(user.Username))
                    {
                        flag = true;
                        break;
                    }
                }
            }
            if (flag)
            {
                return R.Fail("用户名重复");
            }
            else
            {
                client.User = user;
                return R.Success("注册成功");
            }
        }

    }
}
